//
//  GoogleLoginRequest.m
//  iPhoneKML
//
//  Created by Benjamin Blundell on 28/10/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#define DEBUG

#import "GoogleLoginRequest.h"
#import "RegexKitLite.h"

@implementation GoogleLoginRequest

@synthesize logindelegate;

-(id) initWithUsername:(NSString*)user AndPassword:(NSString*)pass {
	
	if (self = [super initWithBaseURL:@"https://www.google.com/accounts/ClientLogin"]) {		 
		 
		 postVars = [[NSMutableDictionary alloc] init];
		 
		 [postVars setObject: @"GOOGLE" forKey: @"accountType"];
		 [postVars setObject: user forKey: @"Email"];
		 [postVars setObject: pass forKey: @"Passwd"];
		 [postVars setObject: @"local" forKey: @"service"];
		 [postVars setObject: @"CASA_iPhone_KML" forKey: @"source"];
		 
		 
		// NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
		 
		 // Set the headers
		 
		 [headerVars setValue:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];

		// [headerVars setValue:postLength forHTTPHeaderField:@"Content-Length"];
		
	
	}
	return self;
}

#pragma mark -
#pragma mark Overides for Callbacks

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[super connectionDidFinishLoading:connection];

#ifdef DEBUG
	NSLog(@"Google Authorization Call Finished");
#endif
	
	
	// Strip the Auth token from the returned data
	NSString *searchString = [self stringData];
	NSString *regexString = @"Auth=.*$"; 

	NSString *matchedString = [searchString stringByMatching:regexString]; 
	
	
	if (matchedString.length > 0){ 
#ifdef DEBUG	
		NSLog(@"matchedString: '%@'", matchedString); 
#endif
		NSString *token =  [matchedString substringFromIndex:5];
		[token retain];
		if (self.logindelegate){
			[logindelegate returnWithToken:token];
		}
	}


	
}


@end
